package com.cndw.kungfu.ext;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.model.Context;

public class UtilsOfBusiness {

	public static void execUpdate(Object source, Map<String, Object> sendMap) {

		Field[] fields = source.getClass().getDeclaredFields();

		if (!BlankUtils.isBlank(source.getClass().getGenericSuperclass())) {
			Field[] superFields = source.getClass().getSuperclass().getDeclaredFields();
			Field[] allFields = new Field[fields.length + superFields.length];
			System.arraycopy(fields, 0, allFields, 0, fields.length);
			System.arraycopy(superFields, 0, allFields, fields.length, superFields.length);
			fields = allFields;
		}

		for (Field e : fields) {
			int modifiers = e.getModifiers();
			if (Modifier.isStatic(modifiers)) {
				continue;
			}
			if (Modifier.isFinal(modifiers)) {
				continue;
			}

			String name = e.getName();
			if (sendMap.containsKey(name)) {

				String param = (String) sendMap.get(name);
				try {
					if (!BlankUtils.isBlank(param)) {
						BeanUtils.setProperty(source, name, param);
					} else if (e.getType() == String.class) {
						BeanUtils.setProperty(source, name, param);
					}
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				} catch (InvocationTargetException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public static Player getPlayer(int style, String param) {
		Player player = null;
		if (style == 1) {
			String SECTION_PATTERN = "^\\d*$";
			Pattern p = Pattern.compile(SECTION_PATTERN);
			Matcher m = p.matcher(param);
			if (m.find()) {
				player = Context.getPlayerServer().getByPlayerId(Long.parseLong(param));
			}
		} else if (style == 2) {
			long playerId = Context.getPlayerServer().getPlayerIdByAccount(param);
			if (playerId != 0) {
				player = Context.getPlayerServer().getByPlayerId(playerId);
			}
		} else if (style == 3) {
			player = Context.getPlayerServer().getByPlayerName(param);
		}
		return player;
	}

	public static long getPlayerId(int style, String param) {
		Player player = getPlayer(style, param);
		if (!BlankUtils.isBlank(player)) {
			return player.getPlayerId();
		}
		return 0;
	}
}
